package priv.happy.java_js_eachother;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.web_view);
        // 加载网页
        webView.loadUrl("file:///android_asset/index.html");
       // 初始化
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webView.addJavascriptInterface(new AndroidToast(), "AndroidToast");

        Button button = findViewById(R.id.call_js);
        button.setOnClickListener(view -> {
            webView.loadUrl("javascript:responseJava('java调用js')");
        });
    }
    public class AndroidToast {
        /**
         * 展示弹窗
         * @param str html页面返回的输入的文本数据
         */
        @JavascriptInterface
        public void show(String str) {
            Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
        }
    }
}